import xbmc
import xbmcgui
import urllib, urllib2
import os, sys, re

__cwd__      = sys.modules[ "__main__" ].__cwd__
__settings__ = sys.modules[ "__main__" ].__settings__
__htm__      = sys.modules[ "__main__" ].__htm__
__test__     = sys.modules[ "__main__" ].__test__
__test_vid__ = sys.modules[ "__main__" ].__test_vid__
__vdata__    = sys.modules[ "__main__" ].__vdata__

class GUI(xbmcgui.WindowXML):
	def __init__(self, *args, **kwargs):
		xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
		self.doModal()

	def onInit(self):
		self.testmode = __settings__.getSetting('testmode')
		self.action_cancel_dialog = (9, 10)
		self.list = self.getControl(52)
		self.list.reset()
		# =================================================================================================
		# Add list items here :
		# if (self.testmode != 'true'):
		if __test__:
			print 'TEST mode'
			__htm__.getPage(url=__cwd__ + '\\samples\\player.htm', txdata=None)
			__htm__.getUserData()
			for i in range(1,11):
				ilabel = 'Item ' + str(i)
				ipath = 'Path ' + str(i)
				img = 'img ' + str(i)
				item = xbmcgui.ListItem(ilabel, ilabel, img, img, ipath )
				item.setProperty('id', 'item_' + str(i))
				self.list.addItem(item)
		# =================================================================================================
		else:
			print 'Loading main page...'
			__htm__.getPage(url='http://www.vplay.ro/serials/', txdata=None)
			__htm__.getUserData()
			items = re.compile('<a href="(.+?)" class="serials-promo-item".+?\n.+?<img src="(.+?)".+?\n.+?<div class="none">(.+?)</div>\n.+?<div class="none">(.+?)\n.+? (.+?)</div>').findall(__htm__.Page)

			self.list.reset()
			for i in items:
				id = i[0].replace('watch','').replace('/','')
				img = i[1]
				ser = i[2].replace('&nbsp;','')
				seas = i[3].replace('&nbsp;','')
				ep = i[4].replace('&nbsp;','')
				item = xbmcgui.ListItem(ser, seas + ' ' + ep, img, img, i[0])
				item.setProperty('id', id)
				self.list.addItem(item)
		# =================================================================================================
		self.getControl(57).setImage(__htm__.UserAvatar)
		self.getControl(58).setLabel(__htm__.UserID)
		self.getControl(59).setLabel(__htm__.UserDays + ' zile VIP')

	def onClick(self, controlId):
		# print 'Control ID : [%s]' % str(controlId)
		if controlId == 9002:
			print 'Favorites'
			import resources.lib.Fav as Fav
			page_fav = Fav.GUI("vplay_fav.xml", __cwd__, "default")
			# self.close()
			
		elif controlId == 9003:
			import resources.lib.GenreList as GenreList
			page_genre_list = GenreList.GUI("vplay_genre_list.xml", __cwd__, "default")
			
		elif controlId == 9004:
			keyboard = xbmc.Keyboard('', 'Enter keyword:', False)
			kw = ''
			canceled = 'false'
			while (kw=='' and canceled=='false') :
				keyboard.doModal()
				if (keyboard.isConfirmed()):
					kw = keyboard.getText()
				if len(kw)==0:
					canceled='true'
			if canceled=='false':
				print 'Keyword : [%s]' % kw
				import resources.lib.Search as Search
				page_search = Search.GUI("vplay_search.xml", __cwd__, "default", keyword=kw)
				
		elif controlId == 9005:
			print 'Login'
			__settings__.openSettings()
			
		elif controlId == 52:
			item = self.list.getSelectedItem()
			# =================================================================================================
			# PLAY the item!
			if not __test__:
				__htm__.getVideo( item.getProperty('id') )
				p = sys.modules[ "__main__" ].vplayer( xbmc.PLAYER_CORE_AUTO, vid=__htm__.VideoUrl, subs=__htm__.Subtitles, id=item.getProperty('id'), listitem=item )
			# =================================================================================================
			else:
				print 'Item : [%s]' % item.getLabel()
				print 'ID   : [%s]' % item.getProperty('id')
			# =================================================================================================

	def onAction(self, action):
		if action in self.action_cancel_dialog:
			self.close()

	def onFocus(self, controlId):
		pass

	# def user(self, page):
		# usr = re.compile('class="username">(.+?)</a>').findall(page)
		# if len(usr)>0: return str(usr[0])
		# else: return 'None'

	# def video_id(self, page):
		# vid = re.compile('"key", "(.+?)"').findall(page)
		# if len(vid)>0: return str(vid[0])
		# else: return 'None'

	# def parse_sub(self, sub):
		# result = ''
		# lines = re.compile('{"s":"(.+?)", "f":(.+?), "t":(.+?)}').findall(sub)
		# index = 1
		# for s, f, t in lines:
			# dt1 = datetime.datetime(1970,1,1) + datetime.timedelta(seconds = int(f))
			# dt2 = datetime.datetime(1970,1,1) + datetime.timedelta(seconds = int(t))
			# result = result + str(index) + '\n' + dt1.strftime('%H:%M:%S,100') + ' --> ' + dt2.strftime('%H:%M:%S,000') + '\n'
			# for ln in s.split('<br>'):
				# result = result + ln + '\n'
			# result = result + '\n'
			# index = index + 1
		# return result
